package com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;

import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.ydkj.a37e_mall.Classes.Applicatiom.MyApplication;
import com.ydkj.a37e_mall.Classes.Model.Request.LoginReq;
import com.ydkj.a37e_mall.Classes.Model.Request.OauthloginReq;
import com.ydkj.a37e_mall.Classes.Model.Response.LoginResp;
import com.ydkj.a37e_mall.R;
import com.ydkj.a37e_mall.Resource.Utils.Async_http_post;
import com.ydkj.a37e_mall.Resource.Utils.CommonUtil;
import com.ydkj.a37e_mall.Resource.Utils.Const;
import com.ydkj.a37e_mall.Resource.Utils.ExampleUtil;
import com.ydkj.a37e_mall.Resource.Utils.GsonImpl;
import com.ydkj.a37e_mall.Resource.Utils.Rsa;
import com.ydkj.a37e_mall.Resource.Utils.SharedPreferencesUtil;
import com.ydkj.a37e_mall.Resource.View.CustomProgressDialog;

import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;

/**
 * Created by Administrator on 2017/1/4.
 */

public class SplashActivity extends BaseActivity {
    Activity mActivity;
    private Handler mHandler;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private MyApplication myApplication;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        mActivity = this;
        initWindow();//沉浸式
        init();
        if (!sharedPreferencesUtil.getOpen_id().equals("")) {
            Oauth_login();
        } else {
            AutoLogin();
        }


    }

    private void init() {
        myApplication = MyApplication.getInstance();
        sharedPreferencesUtil = SharedPreferencesUtil.getInstance(mActivity);
        myApplication = MyApplication.getInstance();

        String deviceId = ExampleUtil.getDeviceId(mActivity.getApplicationContext());
        Log.e("ssss", "channel_id==>" + deviceId);
        myApplication.setChannelID(deviceId);
//        mHandler = new Handler() {
//            @Override
//            public void handleMessage(Message msg) {
//                super.handleMessage(msg);
//                if (msg.what == 1) {
//
//                    Intent intent = new Intent(mActivity, MainActivity.class);
//                    startActivity(intent);
//                    finish();
//                    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
//                }
//            }
//        };
//
//
//        Timer timer = new Timer();
//        TimerTask timerTask = new TimerTask() {
//            @Override
//            public void run() {
//                mHandler.sendEmptyMessage(1);
//            }
//        };
//        timer.schedule(timerTask, 1000);


    }

    private void initWindow() {


        final int sdk = Build.VERSION.SDK_INT;
        Window window = mActivity.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();

        if (sdk >= Build.VERSION_CODES.KITKAT) {
            int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            // 设置透明状态栏
            if ((params.flags & bits) == 0) {
                params.flags |= bits;
                window.setAttributes(params);
            }
        }
    }


    //账号密码登录
    private void AutoLogin() {
        Log.e("ssss1", "账号密码登录==>");
        //通过极光推送获取channelID
        String deviceId = ExampleUtil.getDeviceId(mActivity.getApplicationContext());

        Log.e("ssss1", "channel_id==>" + deviceId);
        myApplication.setChannelID(deviceId);


        LoginReq req = new LoginReq();
        String url = Const.COMMON_ADDRESS + req.urlString();
        req.setMobile(sharedPreferencesUtil.getUsername());
        req.setPassword(sharedPreferencesUtil.getPassword());
        if (!myApplication.getChannelID().equals("")) {
            req.setAlias(myApplication.getChannelID());
        }
        req.setDevice_type(3);
        RequestParams params = new RequestParams();
        try {
            String source = req.getString();
            Rsa rsa = new Rsa();
            Log.e("ssss", "splashlogin==>" + source);

            secret = rsa.encryptByPublic(source);
        } catch (Exception e) {
            e.printStackTrace();
        }
        params.put("secret", secret);
        Async_http_post.post(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                if (errno.equals("000")) {
                    LoginResp resp = GsonImpl.get().toObject(response.toString(), LoginResp.class);
                    sharedPreferencesUtil.setAccessToken(resp.getResult().getAccess_token());
                    myApplication.setDataEntity(resp.getResult().getData());
//                    sharedPreferencesUtil.setIntegral(resp.getResult().getData().getIntegral());

                    pushActivity();
                }
                if (!errno.equals("000")) {
                    pushActivity();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
            }
        });
    }

    //第三方登录
    private void Oauth_login() {
        Log.e("ssss", "第三方登录==>");
//        CustomProgressDialog.createDialog(mActivity).show();
        OauthloginReq req = new OauthloginReq();
        req.setOpenid(sharedPreferencesUtil.getOpen_id());
        req.setType(sharedPreferencesUtil.getType() + "");
        req.setAlias(myApplication.getChannelID());
        req.setDevice_type("3");

        RequestParams params = new RequestParams();
        params.put("secret", req.getSecret());

        Async_http_post.post(Const.COMMON_ADDRESS + req.urlString(), params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
//                CustomProgressDialog.Dismiss();
                String errno = response.optString("errno");
                String errmag = response.optString("errmsg");
                Log.e("url", "第三方==" + response);
                if (errno.equals("000")) {
                    CommonUtil.showToast(mActivity, errmag);
                    LoginResp resp = GsonImpl.get().toObject(response.toString(), LoginResp.class);

                    sharedPreferencesUtil.setAccessToken(resp.getResult().getAccess_token());
                    myApplication.setDataEntity(resp.getResult().getData());

                    pushActivity();
                }
            }


            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接失败");
            }
        });

    }

    public void pushActivity() {
        Log.e("url", sharedPreferencesUtil.getFirstRun() + "");


//        Configuration config = getResources().getConfiguration();
//        DisplayMetrics dm = getResources().getDisplayMetrics();
//        if (sharedPreferencesUtil.getLanguage().equals("CN")) {
//            config.locale = Locale.CHINA; // 设置当前语言配置为简体
//            getResources().updateConfiguration(config, dm); // 更新配置文件
//        } else if (sharedPreferencesUtil.getLanguage().equals("TW")) {
//            config.locale = Locale.TAIWAN; // 设置当前语言配置为繁体
//            getResources().updateConfiguration(config, dm); // 更新配置文件
//        }

        Intent intent = new Intent(mActivity, MainActivity.class);
        startActivity(intent);
        finish();
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
//        } else {
//            Log.e("url", "2");
//            Intent intent = new Intent(mActivity, FirstRun.class);
//            startActivity(intent);
//            finish();
//        }
    }
}
